<template>
  <div class="menu-dialog">
    <el-dialog
      v-model="dialogVisible"
      title="菜单分配"
      width="50%"
      @open="open"
    >
      <div class="dialog-content">
        <el-tree
          ref="treeRef"
          :data="menuList"
          show-checkbox
          default-expand-all
          node-key="menuId"
          highlight-current
          :props="defaultProps"
          :default-checked-keys="roleMenuList"
        />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submit" :loading="isLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import { getAllMenu } from "@/api/menu/index";
import { MenuResponseTree } from "@/api/menu/menu";
import { getRoleMenuList, linkMenu } from "@/api/system/index";
import { convertToNestedArray } from "@/utils/setRoute";
import { ElMessage, ElTree } from "element-plus";
import { computed } from "vue";
defineOptions({
  name: "menuDialog"
});
interface Props {
  roleId: string;
  modelValue: boolean;
}
const props = defineProps<Props>();
const emits = defineEmits(["update:modelValue", "getList"]);
onMounted(() => {
  getALlMenuList();
});
// 获取菜单列表
const menuList = ref<MenuResponseTree[]>();
const getALlMenuList = async () => {
  const res = await getAllMenu();
  if (res.code === 0) {
    menuList.value = convertToNestedArray(res.data);
  }
};
// 获取角色对应的菜单列表
const roleMenuList = ref<string[]>([]);
const getRoleMenuLists = async () => {
  const res = await getRoleMenuList(props.roleId);
  if (res.code === 0) {
    roleMenuList.value = res.data.map(el => el.menuId);
  }
};
// tree树形控间
const treeRef = ref<InstanceType<typeof ElTree>>();
const defaultProps = {
  children: "children",
  label: "name"
};
const dialogVisible = computed({
  get() {
    return props.modelValue;
  },
  set(newValue) {
    emits("update:modelValue", newValue);
  }
});
const open = () => {
  getRoleMenuLists();
};
// 提交
const isLoading = ref(false);
const submit = async () => {
  const menuIdList = treeRef
    .value!.getCheckedNodes(false, true)
    .map(el => el.menuId);
  const data = {
    roleId: props.roleId,
    menuIdList
  };
  isLoading.value = true;
  const res = await linkMenu(data);
  if (res.code === 0) {
    ElMessage.success("分配成功");
    isLoading.value = false;
    dialogVisible.value = false;
    emits("getList");
  }
};
</script>
